package pl.mmadej.ds4java.ds.stack;


import pl.mmadej.ds4java.ds.array.ArrayDecorator;
import pl.mmadej.ds4java.ds.common.DataStructure;

public class ArrayStack<T> extends DataStructure<T> implements Stack<T> {

    private int top;
    private ArrayDecorator<T> array;

    public ArrayStack(int size) {
        array = new ArrayDecorator<T>(size + 1); //with guard
        top = 0;
        array.setAt(0, null);
    }

    @Override
    public T pop() {
        T t = top > 0 ? (T) array.elementAt(top--) : (T) array.elementAt(top);
        array.setAt(top + 1, null);
        return t;
    }

    @Override
    public void push(T t) {
        assertNotNull(t);
        array.setAt(++top, t);
    }

    @Override
    @SuppressWarnings("unchecked")
    public T top() {
        return array.elementAt(top);
    }

    @Override
    public int size() {
        return top;
    }

    @Override
    public boolean empty() {
        return top == 0;
    }

    @Override
    public void clear() {
        array.clear();
        top = 0;
    }

    @Override
    public void reverse() {
        array.reverse(1, top);
    }
}
